local skynet = require "skynet"
local socket = require "socket"
require "skynet.manager"	-- import skynet.register
require "math"
require "public"

local json = require "cjson"
local ErrNo = require "common/ErrNo"
local ROOM_PLAERY_NUM = 4
local MAX_ROOM_NUM = 200000  

CMD = {}
local rooms = {}


--大厅加入房间
function CMD.join_room_hall(data)
	local room_id = math.floor(data.room_id) 
	if not room_id then 
		return nil,nil -- 房间存在
	end
	
	if rooms[room_id] ~= nil then
		return nil,nil -- 房间存在
	end
	local room_info = HALL.get_room('mj_nc',room_id) -- key 游戏类型 mj_nc
	
	if not room_info then 
		return ErrNo.UNKNOW_ERROR,nil
	end
	local room_data = { 
		room_id 	= room_id,  
		optiontype 	= room_info.optiontype,
		playtype 	= room_info.playtype,
		game_type	= 1,
		dizhu		= room_info.integral,
		room_type 	= 2,	
		room_is_double 	= room_info.room_is_double,	
	}
	if rooms[room_id] == nil then 
		local room_id, room_fd = CMD.create_room(room_data)
		return room_id, room_fd
	end
	return room_id,rooms[room_id].room_fd
end

function CMD.create_room(data)
	local room_id = data.room_id
	
	if not room_id then 
		return nil,nil -- 房间存在
	end
	if rooms[room_id] ~= nil then
		return nil,nil -- 房间存在
	end
	
	room_fd = skynet.newservice("majiang_room")

    rooms[room_id] = {}
    rooms[room_id].room_fd = room_fd
    rooms[room_id].count = 1
	if not data.dizhu then 
		data.dizhu = 1
	end
	if not data.room_type then 
		data.room_type = 1 -- 1私房，2.大厅房间
	end
	if not data.total_ju or data.total_ju ~= 12 then 
		data.total_ju = 8
	end
    if data.room_is_double == nil or data.room_is_double ~= 2 then
    	data.room_is_double = 1
    end
    skynet.call( room_fd, "lua", "start", room_id, data.ruleType, data.optionType, data.dizhu, data.room_type, data.total_ju, data.friend_id, data.room_is_double)
    return room_id,room_fd
end

function CMD.join_room(id)
	-- 房间状态
	local room_id = math.ceil(id)
	if rooms[room_id] == nil then
		return ErrNo.ROOM_NOT_EXISTS,nil -- 房间不存在
	end
		
	return room_id,rooms[room_id].room_fd
end


function CMD.join_room_again(room_id,uid)
	local room_id = tonumber(room_id)
	if rooms[room_id] == nil then
		return ErrNo.ROOM_NOT_EXISTS,nil -- 房间不存在
	end
		
	return room_id,rooms[room_id].room_fd
end

function CMD.get_rooms(room_id)
	local room_id = math.ceil(room_id)
	if rooms[room_id] == nil then
		return nil -- 房间不存在
	end 
	return rooms[room_id].room_fd
end


function CMD.room_status(id,data)
    -- skynet.error("room_status id: ",id,"count: ",data.count)
    rooms[id].count = data.count 
end

function CMD.destory(id) 
	if id then 
		local room_id = math.ceil(id)
		-- skynet.call("MG_SAVE", "lua", "clean_room_redis", room_id)
		rooms[id] = nil
	else
		skynet.error("id had destory")
	end
end

skynet.start(function()
	skynet.dispatch("lua", function(_,_, command, ...)
		local f = CMD[command]
		skynet.ret(skynet.pack(f(...)))
	end)
	skynet.register "MAJAING_HALL"
end)

